<?php

namespace App\Http\Controllers\Api\Wechat;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class JsSdkController extends Controller
{
    private $appId;
    private $appSecret;

    public function __construct()
    {
//        $this->appId = config('services.weixin.client_id');
//        $this->appSecret = config('services.weixin.client_secret');
        $this->appId = config('services.weixin.mini_id');
        $this->appSecret = config('services.weixin.mini_secret');
    }

   public function getAccessToken()
   {
       //access_token 存入缓存
       $data = Cache::get('wx_access_token');

       if (!isset($data)) {
           $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
           $res = json_decode($this->httpGet($url));
           $access_token = $res->access_token;
           //存入access_token并设置过期时间（微信access_token保质期为 "2" 小时，所以存入缓存的token要小于两个小时，避免并发时间误差，设置为1小时 ）
           Cache::put('wx_access_token',$access_token,now()->addSeconds(3600));

       }else{

           $access_token = $data;
       }
        Log::info('微信 access_token:'.$access_token);
       return $access_token;
   }



   //curl发送get请求
   public function httpGet($url)
   {
       $curl = curl_init();
       curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
       curl_setopt($curl, CURLOPT_TIMEOUT, 500);
       curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
       curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
       curl_setopt($curl, CURLOPT_URL, $url);

       $res = curl_exec($curl);
       curl_close($curl);

       return $res;
   }
}
